package com.demo.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * AccessServiceImpl
 *
 * @author liujin
 * @date 2020/12/7 23:35
 */
@Component
public class AccessServiceImpl implements AccessService {

    private List<String> list = Arrays.asList("admin", "admin2");



    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        if(!(authentication instanceof OAuth2Authentication)){
            return false;
        }
        String authorization = request.getHeader("Authorization");
        Jwt decode = JwtHelper.decode(authorization.substring("bearer ".length()));
        System.out.println(decode);
        System.out.println(request.getRequestURI());


        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Set<String> authorities = oAuth2Authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());

        //TODO 交集;
        return !Collections.disjoint(list, authorities);
    }
}
